package com.x.xdweb.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.engines.BlowfishEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class UtilHelper {

	public static String decimalStyle_1 = "#0.00";

	public static String decimalStyle_2 = "#0.0000";

	public static String decimalStyle_3 = "######0.00";

	public static String decimalPrecision(Double num, String style) {
		if (num == null)
			num = new Double(0);
		java.text.DecimalFormat df = new java.text.DecimalFormat(style);
		return df.format(num.doubleValue());
	}

	/**
	 * 将输入的科目编号根据级次、编码规则等，输出一个数组，每个元素是科目的各个�?
	 * 
	 * @author LZC
	 * @param kmbh
	 * @param jc
	 * @param bmgz
	 * @return
	 * @throws Exception
	 */
	public static String[] changeKmbhToStringArray(String kmbh, int jc,
			String bmgz) throws Exception {
		String bmgz1 = bmgz.replaceAll(",", "");
		String[] kmbhArray = new String[jc];
		int end = 0;

		// for(int i = 0; i < jc; i++)
		// {
		// kmbhArray[i] = kmbh.substring(end, end + Integer.parseInt("" +
		// bmgz.charAt(i)));
		// end += Integer.parseInt("" + bmgz.charAt(i));
		// }

		for (int i = 0; i < jc; i++) {
			kmbhArray[i] = kmbh.substring(0, end
					+ (Integer.parseInt(bmgz1.charAt(i) + "")));
			end += Integer.parseInt("" + bmgz1.charAt(i));
		}

		return kmbhArray;
	}

	public static String get2bitDay(String day) {
		if (day == null || day.length() < 1 || day.length() > 2) {
			return "01";
		}
		int temp = Integer.parseInt(day);
		if (temp < 1 || temp > 31) {
			return "01";
		}
		if (day.trim().length() < 2) {
			return "0" + day.trim();
		}
		return day;
	}

	/**
	 * 求当前月的上�?个或几个月的时间
	 * 
	 * 例：yearMonth = 200906 iSubtrahend 10 输出�?200808
	 * 
	 * @param yearMonth
	 * @param iSubtrahend
	 * @return
	 * @throws Exception
	 */
	public static String subtractMonth(String yearMonth, int iSubtrahend)
			throws Exception {
		if (iSubtrahend < 0 || iSubtrahend > 12) {
			return yearMonth;
		}

		String[] yearMonthArr = new String[2];
		yearMonthArr[0] = yearMonth.substring(0, 4);
		yearMonthArr[1] = yearMonth.substring(4, 6);

		int iMonth = Integer.parseInt(yearMonthArr[1]);

		String sPreviewMonth = "";

		if (iMonth > iSubtrahend) {
			int iPreviewMonth = iMonth - iSubtrahend;
			String tempPreviewMonth = String.valueOf(iPreviewMonth);
			if (tempPreviewMonth.length() == 1) {
				tempPreviewMonth = "0" + tempPreviewMonth;
			}

			sPreviewMonth = tempPreviewMonth;
		} else {
			int iPreviewMonth = iMonth - iSubtrahend;
			String tempPreviewMonth = String.valueOf(12 + iPreviewMonth);
			if (tempPreviewMonth.length() == 1) {
				tempPreviewMonth = "0" + tempPreviewMonth;
			}
			sPreviewMonth = tempPreviewMonth;
			yearMonthArr[0] = String
					.valueOf(Integer.parseInt(yearMonthArr[0]) - 1);
		}

		yearMonthArr[1] = sPreviewMonth;

		return yearMonthArr[0] + yearMonthArr[1];
	}

	public static String[] calculateKjqj(String kjqjQ, String kjqjZ) {
		int temp = Integer.parseInt(kjqjZ) - Integer.parseInt(kjqjQ) + 1;

		String[] kjqj = new String[temp];

		for (int i = Integer.parseInt(kjqjQ), j = 0; i <= Integer
				.parseInt(kjqjZ); i++, j++)
			kjqj[j] = UtilHelper.get2bitDay(i + "");

		return kjqj;
	}

	/* 加密�?�? */

	/**
	 * 
	 * @param password
	 * @return String
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 *             说明用MD5把密码加�?
	 */
	public static String encryption(String password)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		String newPassword;
		MessageDigest md = MessageDigest.getInstance("MD5");
		newPassword = Base64.encode(md.digest(password.getBytes("UTF-8")));
		return newPassword;
	}

	/**
	 * 加密明文(对称算法)
	 * 
	 * @param mingwen
	 * @return String 密文
	 */
	public static String symEncrypt(String mingwen) {

		UtilHelper cipherTool = new UtilHelper();
		cipherTool.setEngine(new BlowfishEngine());
		cipherTool.setKeyLength(64);
		String keyStr = KEY_STRING;
		cipherTool.init(true, keyStr);
		String miwen = cipherTool.Encrypt(mingwen);
		return miwen;
	}

	/**
	 * 解密密文(对称算法)
	 * 
	 * @param miwen
	 * @return
	 */
	public static String symDencrypt(String miwen) {

		UtilHelper cipherTool = new UtilHelper();
		cipherTool.setEngine(new BlowfishEngine());
		cipherTool.setKeyLength(64);
		String keyStr = KEY_STRING;
		cipherTool.init(false, keyStr);
		String mingwen = cipherTool.Encrypt(miwen);
		return mingwen;
	}

	private static String KEY_STRING = "14028e5c71c8e3878011c8e3cc8e3878613500a24028e5c7011c8e3c613500a2";
	/**
	 * 算法容器
	 */
	private PaddedBufferedBlockCipher cipher = null;

	/**
	 * 密钥的长�?
	 */
	private int keylength;

	/**
	 * 设置Block Cipher的加密引�?, 如IDEA_Engine
	 * 
	 * @param block_cipher_engine
	 *            加密引擎
	 */
	public void setEngine(BlockCipher block_cipher_engine) {
		/*
		 * Setup the DESede cipher engine, create a PaddedBufferedBlockCipher in
		 * CBC mode.
		 */
		cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(
				block_cipher_engine));
	}

	/**
	 * 设置Block Cipher的密钥长�?
	 * 
	 * @param length
	 */
	public void setKeyLength(int length) {
		this.keylength = length;
	}

	/**
	 * 设置密钥
	 * 
	 * @param encrypt
	 *            加密还是解密
	 * @param keyStr
	 *            密钥字符�?
	 */
	public void init(boolean encrypt, String keyStr) {
		/**
		 * 初始化密�?
		 */
		byte[] keybyte = new byte[this.keylength];

		keybyte = Hex.decode(keyStr);// 将密钥加�?
		/**
		 * encrypt = true 加密 encrypt = false 解密
		 */
		cipher.init(encrypt, new KeyParameter(keybyte));
	}

	/**
	 * 加密
	 * 
	 * @param 要加密的字符�?
	 * @return 加密后的密文
	 */
	public String Encrypt(String mingwen) {
		byte[] inblock = mingwen.getBytes();
		byte[] outblock = new byte[cipher.getOutputSize(inblock.length)];
		int outL;
		String s1 = "";
		outL = cipher.processBytes(inblock, 0, inblock.length, outblock, 0);
		try {
			outL = cipher.doFinal(outblock, outL);
		} catch (CryptoException ce) {
			ce.printStackTrace();
		}
		byte[] result = Hex.encode(outblock);
		s1 = new String(result).trim();
		return s1;

	}

	/**
	 * 解密
	 * 
	 * @param miwen
	 *            密文
	 * @return 明文
	 */
	public String Decrypt(String miwen) {
		byte[] inblock = null;
		byte[] outblock = null;
		String s1 = "";
		int outL;
		inblock = Hex.decode(miwen);
		outblock = new byte[cipher.getOutputSize(inblock.length)];
		outL = cipher.processBytes(inblock, 0, inblock.length, outblock, 0);
		try {
			outL = cipher.doFinal(outblock, outL);
			s1 = new String(outblock).trim();
		} catch (CryptoException ce) {
			ce.printStackTrace();
		}
		return s1;
	}

	/* 加密结束 */

	public static void main(String[] args) {
		UtilHelper cipherTool = new UtilHelper();
		cipherTool.setEngine(new BlowfishEngine());
		cipherTool.setKeyLength(64);
		String keyStr = KEY_STRING;
		cipherTool.init(true, keyStr);
		String miwen = cipherTool.Encrypt("7-5-4");
		System.out.println(miwen);

		cipherTool.init(false, keyStr);
		System.out.println(cipherTool.Decrypt(miwen));
	}

	/**
	 * 给定年月, 输出当前月的�?后一�?, 8位日�?
	 */
	public String outputLastDateOfMonth(String yearMonth) throws Exception {
		String year = yearMonth.substring(0, 4);
		String month = yearMonth.substring(4, 6);

		java.util.GregorianCalendar c = new java.util.GregorianCalendar();
		int iyear = Integer.parseInt(year);
		boolean isLeepYear = c.isLeapYear(iyear);

		String sReturn = "";

		if (month.equalsIgnoreCase("1") || month.equalsIgnoreCase("3")
				|| month.equalsIgnoreCase("5") || month.equalsIgnoreCase("7")
				|| month.equalsIgnoreCase("8") || month.equalsIgnoreCase("10")
				|| month.equalsIgnoreCase("12")) {
			sReturn = year + month + "31";
		} else if (month.equalsIgnoreCase("2") || month.equalsIgnoreCase("4")
				|| month.equalsIgnoreCase("6") || month.equalsIgnoreCase("9")
				|| month.equalsIgnoreCase("11")) {
			sReturn = year + month + "31";
		} else if (month.equalsIgnoreCase("2")) {
			/* 瑞年 */
			if (isLeepYear) {
				sReturn = year + month + "29";
			}
			/* 平年 */
			else {
				sReturn = year + month + "28";
			}
		}

		return sReturn;
	}

}
